package service

import (
	"example.com/m/v2/model/mysql"
	"example.com/m/v2/types"
	"gorm.io/gorm"
)

type Template struct {
	BaseService
	db *gorm.DB
}

func NewTemplate(svcCtx *ServiceContext, db *gorm.DB) *Template {
	res := Template{db: db, BaseService: BaseService{svcCtx: svcCtx}}
	return &res
}

func (t *Template) GetById(id int64) *mysql.Template {
	var res mysql.Template
	t.db.Where("id = ?", id).First(&res)
	return &res
}

func (t *Template) GetListByPage(req *types.DesignListReq) (*[]types.TemplatePageDto, int64) {
	var res *[]types.TemplatePageDto
	var total int64
	query := t.db.Model(&mysql.Template{})

	if req.Type != 0 {
		query.Where("type=?", req.Type)
	}

	if req.Cate != 0 {
		query.Where("category=?", req.Cate)
	}

	page := 1
	if req.Page != 0 {
		page = req.Page
	}

	pageSize := 20
	if req.PageSize != 0 {
		pageSize = req.PageSize
	}
	query.Count(&total)
	query.Offset(pageSize * (page - 1)).Limit(pageSize).Find(&res)
	return res, total
}
